package auth

import (
	"cloud-navigation/app/common/request"
	"cloud-navigation/app/common/response"
	"cloud-navigation/app/models"
	"cloud-navigation/app/services"
	"cloud-navigation/global"
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

// 管理员注册
func AdminRegister(c *gin.Context) {
	var form request.Register
	if !services.Request(c, &form) {
		return
	}

	if user, err := services.AdminService.Register(form); err != nil {
		response.BusinessFail(c, err.Error())
	} else {
		services.WriteLogs(c, "新增管理员: id="+strconv.Itoa(int(user.ID.ID)), 0)
		response.Success(c, user)
	}
}

// 管理员登录
func AdminLogin(c *gin.Context) {
	var form request.Login
	if !services.Request(c, &form) {
		return
	}
	if !services.VerifyCaptcha(form.Code, form.Captcha, "admin") {
		response.ValidateFail(c, "验证码错误", response.Validator{
			Field: "captcha", Message: "验证码错误",
		})
		return
	}

	if admin, err := services.AdminService.Login(form); err != nil {
		response.ValidateFail(c, err.Error(), response.Validator{
			Field: "password", Message: err.Error(),
		})
	} else {
		tokenData, _, err := services.JwtService.CreateToken(services.AdminGuardName, &admin)
		if err != nil {
			response.BusinessFail(c, err.Error())
			return
		}
		services.WriteLogs(c, "管理员登录", int(admin.ID.ID))
		response.Success(c, gin.H{
			"user":    admin,
			"token":   tokenData.AccessToken,
			"type":    tokenData.TokenType,
			"expires": tokenData.ExpiresIn,
		})
	}
}

// 管理员退出
func AdminLogout(c *gin.Context) {
	err := services.JwtService.JoinBlackList(c.Keys["token"].(*jwt.Token))
	if err != nil {
		response.BusinessFail(c, "退出失败")
		return
	}
	services.WriteLogs(c, "管理员退出", 0)
	response.Success(c, nil)
}

// 删除管理员
func AdminDelete(c *gin.Context) {
	id := c.Param("id")
	fmt.Println(id)
	err := global.App.DB.Delete(&models.Admin{}, id).Error
	if err != nil {
		fmt.Println(err.Error())
		response.BusinessFail(c, err.Error())
		return
	}
	services.WriteLogs(c, "删除管理员: id="+id, 0)
	response.Success(c, nil)
}
